#!/usr/bin/env php
<?php
/**
 * $Id: identifydaemon.in 3302 2010-08-09 18:39:20Z eldering $
 *
 * Part of the DOMjudge Programming Contest Jury System and licenced
 * under the GNU GPL. See README and COPYING for details.
 */
if ( isset($_SERVER['REMOTE_ADDR']) ) die ("Commandline use only");

require('@domserver_etcdir@/domserver-static.php');
require(ETCDIR . '/domserver-config.php');

define ('SCRIPT_ID', 'identifydaemon');
define ('LOGFILE', LOGDIR.'/identify.log');

require(LIBDIR . '/init.php');

setup_database_connection('jury');

$waittime = 5;

$verbose = LOG_INFO;

if ( AUTH_METHOD!='IPADDRESS' ) {
	error("Only IP-based authentication is supported.");
}

// Tick use required between PHP 4.3.0 and 5.3.0 for handling signals,
// must be declared globally.
if ( version_compare(PHP_VERSION, '5.3', '<' ) ) {
	declare(ticks = 1);
}
initsignals();

logmsg(LOG_NOTICE, "Identify started [DOMjudge/".DOMJUDGE_VERSION."]");

// Constantly check database for queued requests
while ( TRUE ) {

	// Check whether we have received an exit signal
	if ( function_exists('pcntl_signal_dispatch') ) pcntl_signal_dispatch();
	if ( $exitsignalled ) {
		logmsg(LOG_NOTICE, "Received signal, exiting.");
		exit;
	}

	// try to get one
	$row = $DB->q('MAYBETUPLE SELECT * FROM team_identify
	               WHERE status = "new" ORDER BY timestamp ASC LIMIT 1');

	if ( $row ) {
		$login     = $row['login'];
		$ipaddress = $row['ipaddress'];
		$filename  = $row['filename'];

		# TODO: check login and ipadress for sanity.

		logmsg(LOG_INFO, "Starting identification of team %s at %s", $login, $ipaddress);

		$DB->q('UPDATE team_identify SET status = "working", timestamp = NOW()
		        WHERE login = %s AND ipaddress = %s AND status = "new"',
		       $login, $ipaddress);

		// run-callback-script login ip
		$file = USERDIR . '/' . basename($filename);
		system(LIBDIR . "/user_callback.sh $login $file", $retval);

		if ( $retval == 0 ) {
			$DB->q('UPDATE team SET authtoken = %s
			        WHERE login = %s', $ipaddress, $login);

			$DB->q('UPDATE team_identify SET status = "done", timestamp = NOW()
			        WHERE login = %s AND ipaddress = %s AND status = "busy"',
			       $login, $ipaddress);
			logmsg(LOG_INFO, "Identified team %s at %s", $login, $ipaddress);
		} else {
			$DB->q('UPDATE team_identify SET status = "failed", timestamp = NOW()
			        WHERE login = %s AND ipaddress = %s AND status = "busy"',
			       $login, $ipaddress);
			logmsg(LOG_WARN, "Failed to identify team %s at %s (returned %i)",
			       $login, $ipaddress, $retval);
		}
	} else {
		if ( ! $waiting ) {
			logmsg(LOG_INFO, "No submissions in queue, waiting...");
			$waiting = TRUE;
		}
		sleep($waittime);
		continue;
	}

	$waiting = FALSE;


	// restart the loop
}
